package com.mxpio.demo.cloud.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;

/**
 * @创建人 gewenzhen
 * @创建时间 2025/2/16
 * @描述
 */
@Configuration
public class GatewaySentinelConfig implements InitializingBean {
    @Override
    public void afterPropertiesSet() {
        initGatewayRules();
        initDegradeRules();
    }

    private void initGatewayRules() {
        // 限流规则示例：对 routeId = "inventory-route" 的 QPS 做限制
        GatewayFlowRule rule = new GatewayFlowRule("inventory-route")
                .setCount(10)       // QPS 阈值
                .setIntervalSec(1); // 统计时间窗口(秒)

        GatewayRuleManager.loadRules(Collections.singleton(rule));
    }

    private void initDegradeRules() {
        DegradeRule rule = new DegradeRule("inventory-route")
                .setGrade(RuleConstant.DEGRADE_GRADE_RT)   // 基于响应时间RT
                .setCount(2000)                            // RT 阈值，ms
                .setTimeWindow(10);                        // 熔断持续时间，秒

        DegradeRuleManager.loadRules(Collections.singletonList(rule));
    }
}
